package com.cart.services;

import com.cart.pojo.CartItem;
import com.cart.pojo.OrderHistory;
import com.cart.utils.FileUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class OrderHistoryRepositoryImpl implements OrderHistoryRepository {

    private List<OrderHistory> orderHistories = new ArrayList<>();
    private final String ORDER_HISTORY_FILE = "order_history"; // 订单历史数据文件

    @Override
    public void saveOrder(OrderHistory orderHistory) {
        orderHistories.add(orderHistory);
    }

    @Override
    public List<OrderHistory> findAll() {
        return new ArrayList<>(orderHistories);
    }
    // 在启动时读取数据
    public OrderHistoryRepositoryImpl() throws InvocationTargetException {
        List<OrderHistory> loadedOrderHistories = FileUtil.readFromFile(ORDER_HISTORY_FILE, OrderHistory.class);
        if (loadedOrderHistories != null) {
            orderHistories = loadedOrderHistories;
        }
    }

    @Override
    public List<OrderHistory> findByUserId(int userId) {
        List<OrderHistory> userOrders = new ArrayList<>();
        for (OrderHistory history : orderHistories) {
            if (history.getUserId() == userId) {
                userOrders.add(history);
            }
        }
        return userOrders;
    }

    @Override
    public void createOrder(int userId, List<CartItem> cartItems) {
        OrderHistory history = new OrderHistory(
                userId,
                cartItems,
                new java.util.Date() // 记录购买时间
        );
        orderHistories.add(history);
    }


    // 程序退出时将订单历史保存到文件
    public void saveToFile() {
        FileUtil.writeToFile(ORDER_HISTORY_FILE, orderHistories);
    }
}
